# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


# 思路:闭合为环
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next or k == 0:
            return head
        p, p1, p2 = head, head, head

        # 统计链表长度
        length = 0
        while p:
            length += 1
            p = p.next

        while p2.next:
            p2 = p2.next
        p2.next = p1
        for _ in range(length - k % length):
            p1 = p1.next
            p2 = p2.next
        p2.next = None
        return p1
